package com.team9.fitness.mapper;

import com.team9.fitness.entity.PostLike;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 帖子点赞数据访问层接口
 * 
 * 提供帖子点赞数据的CRUD操作：
 * - 点赞管理：添加、更新、删除点赞记录
 * - 查询功能：支持按用户、帖子、状态查询
 * - 统计功能：统计帖子的点赞数量
 * - 状态管理：支持点赞、取消点赞状态切换
 */
@Mapper
public interface PostLikeMapper {

    @Insert("INSERT INTO post_like (user_id, post_id, is_liked, created_at) " +
            "VALUES (#{userId}, #{postId}, #{isLiked}, NOW()) " +
            "ON DUPLICATE KEY UPDATE is_liked = #{isLiked}, created_at = NOW()")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertOrUpdate(PostLike postLike);

    @Select("SELECT * FROM post_like WHERE id = #{id}")
    PostLike selectById(Long id);

    @Select("SELECT * FROM post_like WHERE user_id = #{userId} AND post_id = #{postId}")
    PostLike selectByUserIdAndPostId(Long userId, Long postId);

    @Select("SELECT * FROM post_like WHERE post_id = #{postId} AND is_liked = TRUE")
    List<PostLike> selectLikedByPostId(Long postId);

    @Select("SELECT * FROM post_like WHERE user_id = #{userId} AND is_liked = TRUE")
    List<PostLike> selectLikedByUserId(Long userId);

    @Select("SELECT COUNT(*) FROM post_like WHERE post_id = #{postId} AND is_liked = TRUE")
    int countLikesByPostId(Long postId);

    @Select("SELECT COUNT(*) FROM post_like WHERE user_id = #{userId} AND is_liked = TRUE")
    int countLikesByUserId(Long userId);

    @Update("UPDATE post_like SET is_liked = #{isLiked}, created_at = NOW() " +
            "WHERE user_id = #{userId} AND post_id = #{postId}")
    int updateLikeStatus(Long userId, Long postId, Boolean isLiked);

    @Delete("DELETE FROM post_like WHERE id = #{id}")
    int deleteById(Long id);

    @Delete("DELETE FROM post_like WHERE user_id = #{userId} AND post_id = #{postId}")
    int deleteByUserIdAndPostId(Long userId, Long postId);

    @Delete("DELETE FROM post_like WHERE post_id = #{postId}")
    int deleteByPostId(Long postId);
}
